<template>
  <div class="container">
    <div class="batch">
      <a-row>
        <a-col :span="4">
          <zhibo :form.sync="planUnitForm" />
        </a-col>
        <a-col :span="4" class="offset">
          <originality :form.sync="originalityForm" />
        </a-col>
        <a-col :span="8" class="offset">
          <pic :form.sync="picForm" />
        </a-col>
        <a-col :span="8" class="offset">
          <myVideo :form.sync="myVideoForm" />
        </a-col>
      </a-row>
      <a-popconfirm title="确定提交？" ok-text="异步提交" cancel-text="提交" @confirm='submitSync' @cancel="submit" style="margin-top: 20px;">
        <a-button type="primary" :loading="loading">
          提交
        </a-button>
      </a-popconfirm>
      <!-- <a-popconfirm title="确定提交？" ok-text="提交" cancel-text="取消" @confirm='submitSync' style="margin-left: 5px;margin-top: 20px;">
        <a-button type="primary" :loading="loading">
          异步提交
        </a-button>
      </a-popconfirm> -->
      <a-popconfirm title="确定返回？" ok-text="返回" cancel-text="取消" @confirm='back' style="margin-left: 5px;">
        <a-button style="box-sizing: content-box;">返回</a-button>
      </a-popconfirm>
      <a-tooltip v-if="last_time" style="margin-left: 10px;">
        <template slot="title">
          <span>上次提交时间：{{ last_time }}</span>
        </template>
        <a-icon type="info-circle" />
      </a-tooltip>
    </div>
  </div>
</template>

<script>
import zhibo from './components/zhibo'
import originality from './components/originalityZhibo'
import pic from './components/pic'
import myVideo from './components/video'
import {oneClickCreate,asyncOneClickCreate, getLastSubmitTime} from '@/api/dianshang/dianshang'

export default {
  data() {
    return {
      planUnitForm:{},
      originalityForm:{},
      picForm: [],
      myVideoForm: [],
      loading: false,
      last_time:'',
    }
  },
  created() {
    this.getLastSubmitTime()
  },
  methods:{
    submit(){
      let params = {
        ...this.planUnitForm,
        ...this.originalityForm,
        picList: this.picForm,
        videoList: this.myVideoForm
      }
      let fd = this.getFormData(params)
      // for (let [a, b] of fd.entries()) {
      //   console.log(a, b, '--------------');
      // } 
      this.loading = true
      oneClickCreate(fd).then((res) => {
        console.log(res)
        this.loading = false
        if(res.errcode == 0){
          this.$message.success('提交成功')
          this.getLastSubmitTime()
        }
      }).catch((err) => {
        console.log(err)
        this.loading = false
      });
    },
    async submitSync(){
      let params = {
        ...this.planUnitForm,
        ...this.originalityForm,
        picList: this.picForm,
        videoList: this.myVideoForm
      }
      let loop = 0
      let status = 'success'
      let destAccountIds = params.destAccountIds
      let funcList = []
      if(destAccountIds){
        funcList = destAccountIds.map(()=>asyncOneClickCreate)
      }
      this.loading = true
      // console.log(params, destAccountIds, funcList, asyncOneClickCreate)
      await funcList.reduce(
        (preFunc, func) => preFunc.then(()=>{
          let _params = params
          _params.destAccountIds = destAccountIds[loop]
          let fd = this.getFormData(params)
          loop++
          return func(fd)
        }).catch((err)=>{
          console.log(err)
          status = 'error'
          this.loading = false
        }),
        Promise.resolve()
      ) 
      this.loading = false
      if(status == 'success'){
        this.$message.success('一键创建商品计划已成功放入队列^_^')
        this.getLastSubmitTime()
      }

      // let fd = this.getFormData(params)
      // this.loading = true
      // asyncOneClickCreate(fd).then((res) => {
      //   this.loading = false
      //   if(res.errcode == 0){
      //     this.$message.success(res.errmsg)
      //   }
      // }).catch(() => {
      //   this.loading = false
      // });
    },
    getLastSubmitTime() {
      getLastSubmitTime().then((res) => {
        if (res.errcode == 0) {
          this.last_time = res.data.last_time
        }
      }).catch(() => {
        
      });
    },
    getFormData(params){
      var fd = new FormData();
      for(let [key, value] of Object.entries(params)){
        if(key == "picList"){
          for(let [, i] of Object.entries(value)){
            // console.log(key+idx, i)
            // fd.append(key+"["+idx+"]", i)
            // let fileName = new Date().valueOf() + Math.floor(Math.random()*(100000-1)+1) + '.' +i.type.split('/')[1]
            fd.append(key+"[]", i.blob, i.name)
          }
        }else if(key == 'userPortrait'){
          if(value.blob == ""){break;}
          fd.append(key+"[]", value.blob, value.name)
        }else if(key == 'custom' || key == 'program' || key == 'zhibo'){
          let v = {}
          value.forEach(e => {
            v[e['key']] = e
          });
          fd.append(key, JSON.stringify(v))
        }else if(key == 'videoList'){
          fd.append(key, JSON.stringify(value))
        }else if(key == 'biaoti' || key == 'describe'){
          fd.append(key, value.join('||'))
        }
        else{
          fd.append(key, value)
        }
      }
      return fd
    },
    back(){
      this.$router.back(-1)
    },
  },
  components:{zhibo, originality, pic, myVideo}
}
</script>

<style lang="less" scoped>
.container{
  background-color: #f0f2f5;
  height: 100vh;
  overflow: hidden;
  .batch{
    width: 1460px;
    margin: 100px auto 0;
    background-color: #ffffff;
    height: 450px;
  }
  .offset{
    margin-left: -1px;
  }
}
</style>
